<?php
class Common_CommandLine
{
    private $arr_options = array();

    public function __construct() {
        $this->arr_options = $this->parseParameters();
    }

    public function getOption($name, $mix_default = null)
    {
        if (array_key_exists($name, $this->arr_options)) {
            return $this->arr_options[$name];
        }

        return $mix_default;
    }

    public function getOptions() {
        return $this->arr_options;
    }

    public function parseParameters($noopt=array())
    {
        $result = array();

        if (isset($GLOBALS['argv'])) {
            $params = $GLOBALS['argv'];
        } else {
            $params = array();
            if(isset($_GET)) {
                // running in a sandbox?
                foreach ($_GET as $k => $v) {
                    $params[] = '--' . $k . '=' . $v;
                }
            }
        }

        reset($params);
        while (list($tmp, $p) = each($params)) {
            if ($p{0} == '-') {
                $pname = substr($p, 1);
                $value = true;
                if ($pname{0} == '-') {
                    // long-opt (--<param>)
                    $pname = substr($pname, 1);
                    if (strpos($p, '=') !== false) {
                        // value specified inline (--<param>=<value>)
                        list($pname, $value) = explode('=', substr($p, 2), 2);
                    }
                }
                // check if next parameter is a descriptor or a value
                $nextparm = current($params);
                if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params);
                $result[$pname] = $value;
            } else {
                // param doesn't belong to any option
                $result[] = $p;
            }
        }
        return $result;
    }
}
